package com.example.demo.controller;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.example.demo.entity.AlipayBean;
import com.example.demo.entity.Order;
import com.example.demo.entity.Orderdetail;
import com.example.demo.service.AlipayService;
import com.example.demo.service.IOrderService;
import com.example.demo.utils.PassToken;
import com.example.demo.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * orderController
 * 
 * @author ruoyi
 * @date 2025-05-15
 */
@RestController
@RequestMapping("/system/order")
public class OrderController
{
    @Autowired
    private IOrderService orderService;




    /**
     * 查询order列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @PassToken
    @GetMapping("/list")
    public ResponseResult list(Order order)
    {
//        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return ResponseResult.createBySuccess(200,list,"查询成功");
    }


    @PassToken
    @GetMapping(value = "/getOrders/{ordersn}")
    public ResponseResult getOrders(@PathVariable("ordersn") String ordersn) {
        return ResponseResult.createBySuccess(200, orderService.getOrdersByOrdersn(ordersn), "获取成功");

    }

    @PassToken
    @GetMapping(value = "/getstate/{userid}")
    public ResponseResult getstate(@PathVariable("userid") Long userid) {
        System.out.println(userid);
        List<Order> list = orderService.selectOrderBystate(userid);
        return ResponseResult.createBySuccess(200, list, "获取成功");

    }

    /**
     * 导出order列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:export')")
//    @Log(title = "order", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Order order)
//    {
//        List<Order> list = orderService.selectOrderList(order);
//        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
//        util.exportExcel(response, list, "order数据");
//    }

    /**
     * 获取order详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{orderid}")
    public ResponseResult getInfo(@PathVariable("orderid") Long orderid)
    {
        Order order = orderService.selectOrderByOrderid(orderid);
        return ResponseResult.createBySuccess(200,order,"查询成功");
    }

    /**
     * 新增order
     */
//    @PreAuthorize("@ss.hasPermi('system:order:add')")
//    @Log(title = "order", businessType = BusinessType.INSERT)
    @PassToken
    @PostMapping
    public ResponseResult add(@RequestBody Order order)
    {
        System.out.println(order.getOrdersn());
        String ordersn = UUID.randomUUID()+"";           // System.currentTimeMillis();  // 20250508+(Math.random()*100000)
        order.setOrdersn(ordersn);  //订单编号是随机产生的，前端产生可以，后端也可以产生
        List<Orderdetail> list = order.getOrderdetailsList();
        System.out.println(list);
        if(list == null ){
            System.out.println("获取不到");
        }
        for(Orderdetail od:list){
            od.setOrdersn(ordersn);
        }

        System.out.println(order.getOrdersn());
        System.out.println(order.getOrderdetailsList().size());
        int i = orderService.insertOrder(order);
        if (i > 0) {
            return ResponseResult.createBySuccess(200, ordersn, "添加成功");
        } else {
            return ResponseResult.createByFail(500, "添加失败");
        }
    }

    /**
     * 修改order
     */
//    @PreAuthorize("@ss.hasPermi('system:order:edit')")
//    @Log(title = "order", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseResult edit(@RequestBody Order order)
    {

        int i = orderService.updateOrder(order);
        if (i>0){
            return  ResponseResult.createBySuccess(200,"","添加成功");
        }else{
            return  ResponseResult.createByFail(200,"添加失败");
        }


    }

    /**
     * 删除order
     */
//    @PreAuthorize("@ss.hasPermi('system:order:remove')")
//    @Log(title = "order", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderids}")
    public ResponseResult remove(@PathVariable Long[] orderids)
    {
        int i =orderService.deleteOrderByOrderids(orderids);
        if (i>0){
            return  ResponseResult.createBySuccess(200,"","添加成功");
        }else{
            return  ResponseResult.createByFail(200,"添加失败");
        }
    }




    @Autowired
    AlipayService alipayService;

    @PassToken
    @GetMapping("/pay")
    public String payOrders(String outTradeNo, String subject, String totalAmount, String body, HttpServletRequest response) throws AlipayApiException {
        System.out.println(123);
        System.out.println(outTradeNo+"............");
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);
        // String s =alipayService.aliPay(alipayBean);
        //  return ResponseResult.createBySuccess(200, s, "返回数据成功");
        return alipayService.alipay(alipayBean);
    }


    @PassToken
    @GetMapping("/alipay_back")
    public String alipayback(@RequestParam Map<String,String> params, HttpServletRequest request){
        //订单号
        String orderNo = params.get("out_trade_no");   //很重要
        //支付宝的交易号
        String tradeNo = params.get("trade_no");
        //支付宝的交易状态
        String tradeStatus = params.get("trade_status");
        System.out.println(orderNo+"         "+tradeNo+"          "+tradeStatus);
        //  Orders o = new Orders();
        // o.setOrdersn(orderNo);
        // Orders order = ordersService.selectOrdersList(o,1,1).getRows().get(0);
        Order order = orderService.getOrdersByOrdersn(orderNo);  //根据ordersn获取Orders对象
        if(order!=null){
            order.setState(new Long(1));
            int i= orderService.updateOrder(order);  //更新订单的状态
            System.out.println(i+"     ");
            //商品的库存的修改

        }
        return "支付成功";
    }
}
